package partner_domains

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
	"strconv"
)

var CacheKeyPrefix = TableName + "_"

// @title GetAllPartnerDomainFromCache
// @description 如果缓存不存在　则从数据库取
// @return map[int64]*PartnerDomains
func GetAllPartnerDomainFromCache(dc model.DbContext) (map[int64]*PartnerDomains, error) {
	redisOp := dc.GetRedisConn()
	key := CacheKeyPrefix + "all"
	data, errGet := redisOp.Get(key)
	if errGet != nil {
		if errGet == redis.Nil {

			data, errDb := GetAllItemsFromDb()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			errSet := redisOp.Set(key, string(jsonData), 0)
			if errSet != nil {
				return nil, errSet
			}

			return data, nil
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData map[int64]*PartnerDomains
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @description 如果缓存不存在　这个返回的是map
// @return map[string]string
func GetAllPartnerDomainMapFromCache(dc model.DbContext) (map[string]string, error) {
	redisOp := dc.GetRedisConn()
	key := CacheKeyPrefix + "_map_all"
	data, errGet := redisOp.HGetAll(key)
	if errGet != nil {
		if errGet == redis.Nil {

			data, errDb := GetAllItemsFromDb()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			// 没有数据
			if len(data) == 0 {
				return map[string]string{}, nil
			}

			mapData := make(map[string]string)
			for i, v := range data {
				mapData[v.Domain] = strconv.FormatInt(i, 10)
			}

			errSet := redisOp.HSet(key, mapData)
			if errSet != nil {
				return nil, errSet
			}

			return mapData, nil
		}
		panic("Redis-" + errGet.Error())
	}

	return data, nil
}

// @title GetPartnerIdByHostFromCache
// @description 获取租户的ID, 通过host
// @return map[string]string
func GetPartnerIdByHostFromCache(host string) (int64, error) {
	redisOp := credis.New()
	key := CacheKeyPrefix + "_map_all"
	idStr, errGet := redisOp.HGet(key, host)

	if errGet != nil {
		if errGet == redis.Nil {

			// 获取单个域名对象
			domain, errDb := GetItemsByDomain(host)
			if errDb != nil {
				return 0, app.NewError(errDb)
			}

			mapData := make(map[string]interface{})
			mapData[domain.Domain] = domain.PartnerId

			errSet := redisOp.HSet(key, mapData)
			if errSet != nil {
				return 0, app.NewError(errSet)
			}

			return domain.PartnerId, nil
		}
		panic("Redis-" + errGet.Error())
	}

	idInt64, _ := strconv.ParseInt(string(idStr), 10, 64)

	return idInt64, nil
}
